package com.yang.simple_rpc.config;

import com.yang.simple_rpc.client.ClientProxyFactory;
import com.yang.simple_rpc.client.discovery.ZkServiceDiscovery;
import com.yang.simple_rpc.client.net.NettyNetClient;
import com.yang.simple_rpc.common.protocol.MessageProtocol;
import com.yang.simple_rpc.common.protocol.SerializeMessageProtocol;
import com.yang.simple_rpc.properties.SimpleRpcProperty;
import com.yang.simple_rpc.server.NettyRpcServer;
import com.yang.simple_rpc.server.RequestHandler;
import com.yang.simple_rpc.server.RpcServer;
import com.yang.simple_rpc.server.register.DefaultRpcProcessor;
import com.yang.simple_rpc.server.register.ServiceRegister;
import com.yang.simple_rpc.server.register.ZookeeperExportServiceRegister;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * Spring Boot 自动配置类
 * @author : morikawaaaa
 * @date : 2022
 */
@Configuration
public class AutoConfiguration {

    @Bean
    public DefaultRpcProcessor defaultRpcProcessor(){
        return new DefaultRpcProcessor();
    }

    public ClientProxyFactory clientProxyFactory(@Autowired SimpleRpcProperty simpleRpcProperty){
        ClientProxyFactory fac = new ClientProxyFactory();
        fac.setSid(new ZkServiceDiscovery(simpleRpcProperty.getRegisterAddress()));

        Map<String, MessageProtocol> supportMessageProtocol = new HashMap<>();

        supportMessageProtocol.put(simpleRpcProperty.getProtocol(), new SerializeMessageProtocol());

        fac.setSupportMessageProtocol(supportMessageProtocol);


        //设置网络层实现
        fac.setNetClient(new NettyNetClient());
        return fac;

    }

    @Bean
    public ServiceRegister serviceRegister(@Autowired SimpleRpcProperty simpleRpcProperty){
        return new ZookeeperExportServiceRegister(
                simpleRpcProperty.getRegisterAddress(),
                simpleRpcProperty.getServerPort(),
                simpleRpcProperty.getProtocol());
    }

    @Bean
    public RequestHandler requestHandler(@Autowired ServiceRegister serviceRegister){
        return new RequestHandler(new SerializeMessageProtocol(), serviceRegister);
    }


    @Bean
    public SimpleRpcProperty simpleRpcProperty(){
        return new SimpleRpcProperty();
    }

    public RpcServer rpcServer(@Autowired RequestHandler requestHandler, @Autowired SimpleRpcProperty simpleRpcProperty){
        return new NettyRpcServer(simpleRpcProperty.getServerPort(), simpleRpcProperty.getProtocol(), requestHandler);
    }
}
